package com.my;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by YJH on 2017/7/13 10:29.
 */
public class LoginServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName = request.getParameter("method");

        try {
            Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取user
        String name = request.getParameter("name");
        //2.调用UserDao获取用信息， 把用户信息放入到HttpSession中
        User user = userDao.get(name);
        request.getSession().setAttribute("user", user);
        //3.重定向到articles.jsp
        response.sendRedirect(request.getContextPath() + "/articles.jsp");
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取HttpSession
        HttpSession session = request.getSession();
        //2.使HttpSession失效
        session.invalidate();
        //3.重定向到/login.jsp
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }
}
